<template>
	<view class="merchant-container">
		<uv-toast ref="toast"></uv-toast>
		<PLoader :loading="loading" background-color="#00000060"></PLoader>
		<!-- 顶部店铺图片 -->
		<view class="header-image">
			<image :src="merchantInfo.image || '/static/lyf.jpg'" mode="aspectFill"></image>
			<view class="status-tag" :class="{ active: merchantInfo.status === 1 }">
				{{ merchantInfo.status === 1 ? '营业中' : '休息中' }}
			</view>
		</view>

		<!-- 基本信息卡片 -->
		<view class="info-card">
			<view class="store-name">{{ merchantInfo.name }}</view>
			<view class="merchant-name">{{ merchantInfo.merchantName }}</view>
			<view class="rating-info">
				<text class="opening-hours">营业时间：{{ merchantInfo.openingHours }}</text>
				<text class="join-time">入驻时间：{{ formatDate(merchantInfo.createTime) }}</text>
			</view>
		</view>

		<!-- 地址信息 -->
		<view class="address-card">
			<view class="card-title">店铺地址</view>
			<view class="address-content">
				<text class="value">{{ merchantInfo.province }}{{ merchantInfo.city }}{{ merchantInfo.district }}{{
					merchantInfo.street }}</text>
			</view>
		</view>

		<!-- 商家介绍 -->
		<view class="desc-card">
			<view class="card-title">商家介绍</view>
			<view class="desc-content">{{ merchantInfo.des }}</view>
		</view>

		<view class="breakfast-coupon">
			<view class="coupon-content">
				<view class="coupon-left">
					<uv-icon name="gift-fill" size="60" color="#fff"></uv-icon>
					<text class="desc">早餐券</text>
				</view>
				<view class="coupon-right">
					<text class="title">免费早餐券</text>
					<text class="subtitle">每日0:00-10:00可兑换</text>
					<button class="exchange-btn" @tap="watchVideo">
						<uv-icon name="play-circle" size="24" color="#ff5722" class="btn-icon"></uv-icon>
						<text>观看视频获取</text>
					</button>
				</view>
			</view>
		</view>

		<!-- 路线模块 -->
		<view class="map-section">
			<view class="card-title">骑行路线</view>
			<map class="route-map" :latitude="Number(merchantInfo.latitude)" :longitude="Number(merchantInfo.longitude)"
				:markers="markers" :polyline="polyline" :scale="13" show-location>
				<view class="route-info">
					<view class="info-item" v-if="routeInfo">
						<text class="label">预计时间</text>
						<text class="value">{{ Math.ceil(routeInfo.duration) }}分钟</text>
					</view>
					<view class="info-item" v-if="routeInfo">
						<text class="label">骑行距离</text>
						<text class="value">{{ (routeInfo.distance / 1000).toFixed(1) }}公里</text>
					</view>
				</view>
			</map>
			<view class="nav-btn" @tap="openNavigation">
				<uv-icon name="map" size="24" color="#fff" class="btn-icon"></uv-icon>
				<text>打开导航</text>
			</view>
		</view>

		<!-- 广告模块 -->
		<view class="ad-section">
			<view class="card-title">店铺活动</view>
			<view class="ad-list">
				<view v-for="ad in adList" :key="ad.id" class="ad-card">
					<image :src="ad.image" mode="aspectFill" class="ad-image"></image>
					<view class="ad-info">
						<view class="ad-title">{{ ad.title }}</view>
						<view class="ad-desc">{{ ad.description }}</view>
						<view class="ad-price">¥{{ ad.price }}</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			loading: false,

			merchantInfo: {},
			adList: [{
				id: 1,
				title: '新春特惠套餐',
				description: '春节特惠，双人套餐仅需99元',
				image: '/static/lyf.jpg',
				price: 99
			},
			{
				id: 2,
				title: '限时折扣券',
				description: '下单立减30元，全场通用',
				image: '/static/lyf.jpg',
				price: 30
			}
			],
			markers: [],
			polyline: [],
			routeInfo: null,
			routeSteps: [],
			userLocation: null
		}
	},
	methods: {
		showToast(msg, type = 'default', duration = 2000) {
			this.$refs.toast.show({
				message: msg,
				type: type,
				duration: duration,
			})
		},
		formatDate(date) {
			if (!date) return '';
			const d = new Date(date);
			const year = d.getFullYear();
			const month = String(d.getMonth() + 1).padStart(2, '0');
			const day = String(d.getDate()).padStart(2, '0');
			return `${year}年${month}月${day}日`;
		},

		async fetchMerchantInfo(merchantId) {
			try {
				this.loading = true;
				const merchant = await this.$http.get(`/merchant/byId?id=${merchantId}`);

				this.merchantInfo = merchant;
			} catch (e) {
				this.showToast('获取详情失败', 'default', 1000);
				uni.navigateBack();
			} finally {
				this.loading = false;
			}
		},

		// 验证经纬度是否有效
		isValidLatLng(lat, lng) {
			const validLat = lat >= -90 && lat <= 90;
			const validLng = lng >= -180 && lng <= 180;
			return validLat && validLng && !isNaN(lat) && !isNaN(lng);
		},

		async getRouteInfo() {
			if (!this.userLocation) {
				try {
					const location = await uni.getLocation({
						type: 'gcj02'
					});
					this.userLocation = location;
				} catch (e) {
					this.showToast('获取位置失败', 'error');
					return;
				}
			}

			// 验证经纬度
			const startLat = Number(this.userLocation.latitude);
			const startLng = Number(this.userLocation.longitude);
			const endLat = Number(this.merchantInfo.latitude);
			const endLng = Number(this.merchantInfo.longitude);

			if (!this.isValidLatLng(startLat, startLng) || !this.isValidLatLng(endLat, endLng)) {
				this.showToast('位置信息无效', 'error');
				return;
			}

			try {
				const res = await this.$http.get(
					`/wechat/user/route/merchant?latitude=${startLat}&longitude=${startLng}&toLatitude=${endLat}&toLongitude=${endLng}`
				);

				if (res.result?.routes?.[0]) {
					const route = res.result.routes[0];
					this.routeInfo = {
						distance: route.distance,
						duration: route.duration
					};
					this.routeSteps = route.steps;

					// 设置路线
					this.polyline = [{
						points: this.convertPolyline(route.polyline),
						color: '#3C9CFF',
						width: 6,
						arrowLine: true,
						borderWidth: 2,
						borderColor: '#fff'
					}];

					// 设置起点终点标记
					this.markers = [{
						id: 1,
						latitude: this.userLocation.latitude,
						longitude: this.userLocation.longitude,
						iconPath: '/static/location.png',
						width: 30,
						height: 30,
						anchor: {
							x: 0.5,
							y: 0.5
						}
					},
					{
						id: 2,
						latitude: Number(this.merchantInfo.latitude),
						longitude: Number(this.merchantInfo.longitude),
						iconPath: '/static/location.png',
						width: 30,
						height: 30,
						anchor: {
							x: 0.5,
							y: 0.5
						}
					}
					];
				}
			} catch (e) {
				this.showToast('获取路线失败', 'error');
			}
		},


		convertPolyline(polyline) {
			if (!polyline || !polyline.length || polyline.length < 2) {
				return [];
			}
			
			// 复制数组避免修改原始数据
			const coords = polyline.map(Number); // 确保所有值都是数字
			
			// 解压缩坐标
			for (let i = 2; i < coords.length; i++) {
				const value = coords[i - 2] + coords[i] / 1000000;
				// 验证解压后的值是否为有效数字
				if (isNaN(value)) {
					console.error('坐标解压失败:', coords[i - 2], coords[i]);
					return [];
				}
				coords[i] = value;
			}
			
			// 转换为地图需要的格式 [{latitude, longitude}, ...]
			const points = [];
			for (let i = 0; i < coords.length; i += 2) {
				const lat = coords[i];
				const lng = coords[i + 1];
				
				// 验证经纬度是否在有效范围内
				if (lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
					points.push({
						latitude: lat,
						longitude: lng
					});
				} else {
					console.error('无效的经纬度:', lat, lng);
					return [];
				}
			}
			
			return points.length > 0 ? points : [];
		},

		openNavigation() {
			uni.openLocation({
				latitude: Number(this.merchantInfo.latitude),
				longitude: Number(this.merchantInfo.longitude),
				name: this.merchantInfo.name,
				address: `${this.merchantInfo.province}${this.merchantInfo.city}${this.merchantInfo.district}${this.merchantInfo.street}`,
				success: () => {

				},
				fail: () => {
					this.showToast('打开导航失败', 'error');
				}
			});
		}
	},

	onLoad(options) {
		if (!options.merchantId) {
			this.showToast('该商户不存在', 'default', 1000);
			uni.navigateBack();
			return;
		}

		this.fetchMerchantInfo(options.merchantId);
	},

	async onReady() {
		if (this.merchantInfo.latitude && this.merchantInfo.longitude) {
			await this.getRouteInfo();
		}
	}
}
</script>

<style lang="scss" scoped>
@import 'merchant_detail.scss';
</style>